﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Hangjing.Model;
using Hangjing.SQLServerDAL;

using System.Text;
using System.Text.RegularExpressions;
using Hangjing.SQLServerDAL.serverinterface;
using Hangjing.Weixin;

/// <summary>
/// 支付
/// </summary>
public partial class AndroidAPI_user_pay : System.Web.UI.Page
{
    public String appId = "";
    public String partner = "";
    public String timeStamp = "";
    public String nonceStr = "";
    public String packageValue = "";
    public String paySign = "";
    public String orderid = "";


    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();

        string shopid = WebUtility.InputText(Request["shopid"]);
        string orderid = WebUtility.InputText(Request["orderid"]);
        string paytype = WebUtility.InputText(Request["paytype"]);
        string payprice = WebUtility.InputText(Request["payprice"]);
        string trade_type = WebUtility.InputText(Request["trade_type"]);
        

      

        if (shopid != "0")
        {
            PointsInfo model = new Points().GetModel(Convert.ToInt32(shopid));
            new TenpayUtil(model.cityid);
        }
        else
        {
            new TenpayUtil(Convert.ToInt32(WebUtility.InputText(Request["cityid"])));
        }

        //添加支付记录，主要用来在支付过程中，失败后，重新支付
        PayOrderLog dalpaylog = new PayOrderLog();
        string payorderid = dalpaylog.GetPayBatch(orderid);

        /*********************准备去支付 添加支付日志********************************/
        PayOrderLogInfo info = new PayOrderLogInfo();
        info.OrderId = orderid;
        info.AddTime = DateTime.Now;
        info.Batch = payorderid;
        info.Price = Convert.ToDecimal(payprice);

        info.PayType = 0;
        info.PayTime = Convert.ToDateTime("1900-1-1");
        info.State = 0;
        info.PayCallTime = Convert.ToDateTime("1900-1-1");
        info.Remark = "";
        info.Reve1 = "5";
        info.Reve2 = "";
        dalpaylog.Add(info);
        /*********************添加支付日志 over********************************/



        timeStamp = TenpayUtil.getTimestamp();
        nonceStr = TenpayUtil.getNoncestr();

        appId = CacheHelper.GetSetValue(18);//小程序版本
        if (trade_type == "APP")
        {
            appId = "wxdb10d38ea232e6cd";
            partner = "1520168951";
        }
        else
        {
            partner = TenpayUtil.partner;
        }

        //步骤2：使用统一支付接口，获取prepay_id
        UnifiedOrder_pub uopay = new UnifiedOrder_pub(Context);
        uopay.rh.setParameter("appid", appId);
        uopay.rh.setParameter("mch_id", partner);
        uopay.rh.setParameter("nonce_str", nonceStr);
        uopay.rh.setParameter("body", "rechange");

        string openid = WebUtility.InputText(Request["openid"]);
        if (openid !=null && openid.Length > 0)
        {
            uopay.rh.setParameter("openid", openid);
        }

        uopay.rh.setParameter("sign_type", "MD5");
       
        uopay.rh.setParameter("out_trade_no", payorderid);
        uopay.rh.setParameter("total_fee", (Convert.ToDecimal(payprice) * 100).ToString("#0"));
        uopay.rh.setParameter("notify_url", TenpayUtil.tenpay_notify);//接收财付通通知的URL
        uopay.rh.setParameter("trade_type", trade_type);
        uopay.rh.setParameter("spbill_create_ip", UserHelp.GetUserIP());

        uopay.rh.setKey(TenpayUtil.key);

        string payresult = uopay.getPrepayId();

        string prepay_id = uopay.prepay_id;

        Dictionary<string, object> dictionary = new Dictionary<string, object>();

        if (prepay_id.Length == 0)
        {
            dictionary.Add("state", "0");
            dictionary.Add("msg", payresult);

            Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(dictionary));
            Response.End();
            return;
        }
        else
        {
            dictionary.Add("state", "1");
            dictionary.Add("msg", "");
        }

        packageValue = "prepay_id=" + prepay_id;

        //步骤3：使用jsapi调起支付(页面中)

        if (trade_type == "APP")
        {
            //设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(Context);
            paySignReqHandler.init();

            paySignReqHandler.setParameter("appid", appId);
            paySignReqHandler.setParameter("partnerid", partner);
            paySignReqHandler.setParameter("prepayid", prepay_id);
            paySignReqHandler.setParameter("package", "Sign=WXPay");
            paySignReqHandler.setParameter("timestamp", timeStamp);
            paySignReqHandler.setParameter("noncestr", nonceStr);
 

            paySignReqHandler.setKey(TenpayUtil.key);

            paySign = paySignReqHandler.createMd5Sign();


            Dictionary<string, string> dictionarySign = new Dictionary<string, string>();
            dictionarySign.Add("appid", appId);
            dictionarySign.Add("partnerid", partner);
            dictionarySign.Add("prepayid", prepay_id);
            dictionarySign.Add("package", "Sign=WXPay");
            dictionarySign.Add("timestamp", timeStamp);
            dictionarySign.Add("noncestr", nonceStr);
            dictionarySign.Add("sign", paySign);

            dictionary.Add("paydata", dictionarySign);


            Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(dictionary));
            Response.End();
        }
        else
        {
            //设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(Context);
            paySignReqHandler.init();

            paySignReqHandler.setParameter("appId", appId);
            paySignReqHandler.setParameter("timeStamp", timeStamp);
            paySignReqHandler.setParameter("nonceStr", nonceStr);

            string package = packageValue;//packageValue.Replace("=", "%3D")

            paySignReqHandler.setParameter("package", package);
            paySignReqHandler.setParameter("signType", "MD5");
            paySignReqHandler.setKey(TenpayUtil.key);

            paySign = paySignReqHandler.createMd5Sign();



            Dictionary<string, string> dictionarySign = new Dictionary<string, string>();
            dictionarySign.Add("appId", appId);
            dictionarySign.Add("timeStamp", timeStamp);
            dictionarySign.Add("nonceStr", nonceStr);
            dictionarySign.Add("package", package);
            dictionarySign.Add("signType", "MD5");

            dictionarySign.Add("paySign", paySign);
            dictionary.Add("paydata", dictionarySign);


            Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(dictionary));
            Response.End();
        }


    }
}
